package cn.yunsenlin.formula.cloud.share;

import cn.yunsenlin.formula.cloud.bean.auth.Template;
import cn.yunsenlin.formula.cloud.interfaces.ShareTemplateService;
import cn.yunsenlin.formula.cloud.interfaces.TemplateService;
import cn.yunsenlin.formula.cloud.mysql.bean.generator.TbTemplate;
import cn.yunsenlin.formula.cloud.mysql.bean.generator.TbTemplateCriteria;
import cn.yunsenlin.formula.cloud.mysql.mapper.generator.TbTemplateMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShareTemplateServiceImpl implements ShareTemplateService {
    private final TemplateService templateService;
    private final TbTemplateMapper tbTemplateMapper;

    @SuppressWarnings("all")
    public ShareTemplateServiceImpl(TemplateService templateService, TbTemplateMapper tbTemplateMapper) {
        this.templateService = templateService;
        this.tbTemplateMapper = tbTemplateMapper;
    }

    @Override
    public boolean templateIsExist(String uuid) {
        TbTemplateCriteria criteria = new TbTemplateCriteria();
        criteria.or().andShareUuidEqualTo(uuid);
        List<TbTemplate> tbTemplates = tbTemplateMapper.selectByExample(criteria);
        return tbTemplates.size()>0;
    }

    @Override
    public boolean templateNeedPassword(String uuid) {
        TbTemplateCriteria criteria = new TbTemplateCriteria();
        criteria.or().andShareUuidEqualTo(uuid);
        List<TbTemplate> tbTemplates = tbTemplateMapper.selectByExample(criteria);
        if(tbTemplates.size()>0){
            return tbTemplates.get(0).getShareEncryption();
        }else{
            return false;
        }
    }

    @Override
    public Template selectByUuid(String uuid) {
        TbTemplateCriteria criteria = new TbTemplateCriteria();
        criteria.or().andShareUuidEqualTo(uuid);
        return selectByCriteria(criteria);
    }

    @Override
    public Template selectByUuid(String uuid, String password) {
        TbTemplateCriteria criteria = new TbTemplateCriteria();
        criteria.or().andShareUuidEqualTo(uuid).andShareEncryptionPasswordEqualTo(password);
        return selectByCriteria(criteria);
    }

    @Override
    public Template copyTemplate(String uuid, int userId) {
        //todo
        return null;
    }

    /**
     * 根据数据库模型查询
     * @param criteria 模型
     * @return 公式信息
     */
    private Template selectByCriteria(TbTemplateCriteria criteria){
        List<TbTemplate> tbTemplates = tbTemplateMapper.selectByExample(criteria);
        if(tbTemplates.size()>0){
            Template template = templateService.selectById(tbTemplates.get(0).getId());
            template.getBaseInfo().setShareEncryptionPassword("******");
            return template;
        }
        return null;
    }
}
